package com.tarena.lbs.user.dao.repository.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.user.dao.mapper.UserGroupMapper;
import com.tarena.lbs.user.dao.repository.UserGroupRepository;
import com.tarena.lbs.user.pojo.po.UserGroupPO;
import com.tarena.lbs.user.pojo.query.UserGroupQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.tarena.lbs.base.protocol.pager.BasePageQuery;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Repository
public class UserGroupRepositoryImpl implements UserGroupRepository {
    @Autowired
    private UserGroupMapper userGroupMapper;


    @Override
    public void save(UserGroupPO po) {
        userGroupMapper.insert(po);
    }

    @Override
    public PageInfo<UserGroupPO> pagesList(UserGroupQuery query) {
        QueryWrapper<UserGroupPO> queryWrapper = assembleUserGroupQuery(query);
        //PageHelper.startPage 之间不能有代码
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<UserGroupPO> pos = userGroupMapper.selectList(queryWrapper);
        //selectList 数据库操作 之间不能有代码
        return new PageInfo<>(pos);
    }

    @Override
    public List<Integer> getGroupIds(List<Integer> tagIds, Integer businessId) {
        List<Integer> groupIds = new ArrayList<>();

        QueryWrapper query = new QueryWrapper();
        query.eq("business_id", businessId);
        query.in("tag_ids", tagIds);

        List<UserGroupPO> ugps = userGroupMapper.selectList(query);
        log.debug("ugps={}", ugps);
        for (UserGroupPO ugp : ugps) {
            groupIds.add(ugp.getId());
        }
        log.debug("groupIds={}", groupIds);
        return groupIds;
    }

    @Override
    public UserGroupPO findById(Long id) {
        return userGroupMapper.selectById(id);
    }

    private QueryWrapper<UserGroupPO> assembleUserGroupQuery(UserGroupQuery query) {
        QueryWrapper<UserGroupPO> queryWrapper = new QueryWrapper<>();
        //1.businessId 商家id 相等查询 where business_id=#{businessId}
        if (query.getBusinessId() != null){
            queryWrapper.eq("business_id",query.getBusinessId());
        }
        if (StringUtils.isNotBlank(query.getGroupName())){
            queryWrapper.like("group_name",query.getGroupName());
        }
        return queryWrapper;
    }
}
